<template>
  <van-form @submit.prevent="onSubmit">

    <van-field name="uploader" label="选择头像">
      <template #input>
        <!--限制上传个数-->
        <van-uploader type="file" v-model="fileList" @change="onFileChange" name="file" multiple :max-count="1" />
      </template>
    </van-field>

    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="button" @click="submitForm">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from "vue-router";
import { ref } from "vue";
import myAxios from "../../plugins/myAxios";
import { Toast } from "vant";
import {getCurrent} from "../../services/currentUser.ts";
const route = useRoute();
const router = useRouter();

const fileList = ref([]);

// 初始化一个空的 FormData 对象
const formData = ref(new FormData());

const file = ref()
// 监听文件输入的变化
const onFileChange = (e: { target: { files: any[]; }; }) => {
  const file = e.target.files[0];
  if (file) {
    formData.value.append('file', file);
  }
};


const onSubmit = async () => {
  const currentUser = await getCurrent();
  if (!currentUser) {
    Toast.fail('用户未登录');
    return;
  }

  // 将用户 ID 添加到 FormData 对象中
  formData.value.append('id', currentUser.id);

  try {
    // 直接将 formData 作为请求体发送
    const res = await myAxios.post('/user/uploadAvatar', formData.value);
    if (res.code === 0 && res.data >0 /* 或者其他表示成功的逻辑 */) {
      Toast.success('修改成功');
      router.back();
    } else {
      Toast.fail(res.description);
    }
  } catch (error) {
    Toast.fail('请求失败');
    console.error(error);
  }
};

// 注意：由于我们使用了 @submit.prevent 阻止表单的默认提交行为，
// 所以我们需要一个单独的方法来触发提交，这里使用了 @click="submitForm"
const submitForm = () => {
  onSubmit();
};
</script>



<style scoped>

</style>
